const Koa = require('koa');
const Router = require('@koa/router');
const bodyParser = require('koa-bodyparser');
const jwt = require('jsonwebtoken');
const cors = require('@koa/cors');

const app = new Koa();
const router = new Router();

// 如果你需要更细粒度配置，比如指定允许的来源和方法：
app.use(cors({
  origin: (ctx) => {
    const allowedOrigins = ['http://localhost:5173']; // 允许的源列表
    if (allowedOrigins.includes(ctx.request.header.origin)) {
      return ctx.request.header.origin;
    }
    return ''; // 不允许跨域访问
  },
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
  credentials: true, // 允许携带 cookie
}));
app.use(bodyParser());


// 模拟数据库：用户、角色、权限
const roles = [
  { id: 1, name: 'admin', menus: [{ name: 'Admin', path: '/Admin', component: 'Admin', children: [] }] },
  { id: 2, name: 'editor', menus: [{ name: 'Admin', path: '/Admin', component: 'Admin', children: [] }] },
];

const users = [
  { id: 1, username: 'admin', password: '123456', roleId: 1 },
  { id: 2, username: 'editor', password: '123456', roleId: 2 },
];

// JWT 秘钥
const SECRET = 'your_secret_key';

// 登录接口
router.post('/api/login', async (ctx) => {
  const { username, password } = ctx.request.body;
  const user = users.find(u => u.username === username);

  if (!user) {
    ctx.status = 401;
    ctx.body = { message: '用户不存在', code: 401 };
    return;
  }

  if (user.password !== password) {
    ctx.status = 401;
    ctx.body = { message: '密码错误', code: 200 };
    return;
  }

  // 登录成功，签发 token
  const token = jwt.sign({ id: user.id, username: user.username, roleId: user.roleId }, SECRET, { expiresIn: '1h' });

  ctx.body = {
    code: 200,
    message: '登录成功',
    token,
  };
});

// 获取用户菜单接口，带身份验证
router.get('/api/menus', async (ctx) => {
  const authHeader = ctx.headers.authorization;
  if (!authHeader) {
    ctx.status = 401;
    ctx.body = { message: '未授权' };
    return;
  }

  const token = authHeader.split(' ')[1];
  try {
    const decoded = jwt.verify(token, SECRET);
    const userRole = roles.find(r => r.id === decoded.roleId);
    if (!userRole) {
      ctx.status = 403;
      ctx.body = { message: '无权限访问' };
      return;
    }

    ctx.body = {
      menus: userRole.menus,
      code: 200,
    };
  } catch (err) {
    ctx.status = 401;
    ctx.body = { message: 'Token无效或已过期' };
  }
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log('服务启动在 http://localhost:3000');
});
